package org.ly.uap.client.session;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class HashMapBackedSessionMappingStorage
        implements SessionMappingStorage {
    private final Map<String, HttpSession> MANAGED_SESSIONS = new HashMap();

    private final Map<String, String> ID_TO_SESSION_KEY_MAPPING = new HashMap();

    private final Log log = LogFactory.getLog(getClass());

    public synchronized void addSessionById(String mappingId, HttpSession session) {
        this.ID_TO_SESSION_KEY_MAPPING.put(session.getId(), mappingId);
        this.MANAGED_SESSIONS.put(mappingId, session);
    }

    public synchronized void removeBySessionById(String sessionId) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("Attempting to remove Session=[" + sessionId + "]");
        }

        String key = (String) this.ID_TO_SESSION_KEY_MAPPING.get(sessionId);

        if (this.log.isDebugEnabled()) {
            if (key != null)
                this.log.debug("Found mapping for session.  Session Removed.");
            else {
                this.log.debug("No mapping for session found.  Ignoring.");
            }
        }
        this.MANAGED_SESSIONS.remove(key);
        this.ID_TO_SESSION_KEY_MAPPING.remove(sessionId);
    }

    public synchronized HttpSession removeSessionByMappingId(String mappingId) {
        HttpSession session = (HttpSession) this.MANAGED_SESSIONS.get(mappingId);

        if (session != null) {
            removeBySessionById(session.getId());
        }

        return session;
    }
}
